<template>
  <div class="role-manage">
    <el-card>
      <div class="desc-box">
        <div class="title">角色列表</div>
        <div class="desc">您可以进行对角色信息进行新增、修改、删除、查询等操作！</div>
      </div>
      <el-button class="add-button" type="primary" @click="openAddAndEditDialog(0)">添加角色</el-button>
    </el-card>

    <el-card class="second-card">
      <el-table
        :data="roleList"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="拼命加载中......"
        :header-cell-class-name="setHeaderRowClassName"
        max-height="530px"
        :header-cell-style="{textAlign:'center'}"
        :cell-style="{textAlign:'center'}">
        <el-table-column type="index" fixed></el-table-column>
        <el-table-column prop="RoleName" label="角色姓名"></el-table-column>
        <el-table-column prop="Describe" label="角色描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="CreationTime" label="创建时间" :formatter="dateFormat"></el-table-column>
        <el-table-column label="启停状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.Status"
              :active-value="1"
              :inactive-value="0"
              @change="statusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="openAddAndEditDialog(scope.row.ID)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteRoles(scope.row)">删除</el-button>
            <el-button type="warning" size="mini" @click="openSetRightsTree(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    分页-->
      <Pagination :child-msg="queryInfo" @callFather="callFather"></Pagination>
    </el-card>

    <add-and-edit-dialog
      v-if="isShowDialogComponent"
      :title="title"
      @handleClose="handleClose"
      :is-show-dialog-component="isShowDialogComponent"
      :judge-id="judgeId">
    </add-and-edit-dialog>

    <!--    分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
      ref="dialogRef">
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="ID"
        default-expand-all
        ref="treeRef"
        show-checkbox
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRights">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
//导入添加和编辑对话框组件
import AddAndEditDialog from './childComps/AddAndEditDialog'
//导入角色管理的类
import RoleManage from '../../model/roleManage'
//导入时间戳转换插件
import moment from 'moment'
//导入分页组件
import Pagination from '../../components/base/pagination/Pagination'

export default {
  name: 'RoleManage',
  components: {
    AddAndEditDialog,
    Pagination
  },
  data () {
    return {
      loading: false,
      roleList: [],
      isShowDialogComponent: false,
      title: '',
      queryInfo: {
        Page: 1,
        Limit: 10,
        total: 0,
      },
      judgeId: 0,
      //控制分配权限对话框的显示与隐藏
      setRightsDialogVisible: false,
      //保存获取的树里面的数据
      rightsList: [],
      treeProps: {
        label: 'JuName',
        children: 'Children'
      },
      //树中被选中的项的id
      defKeys: [],
      roleId: 0,
    }
  },
  created () {
    //调用获取角色列表的方法
    this.getRoleList()
  },

  methods: {
    //设置绑定学科的表头样式
    setHeaderRowClassName ({ rowIndex }) {
      if (rowIndex === 0) {
        return 'setHeaderSubjectColumnName'
      }
    },
    callFather (value) {
      if (value.currentPage) this.queryInfo.Page = value.currentPage
      if (value.pageSize) this.queryInfo.Limit = value.pageSize
      this.getRoleList()
    },
    //时间戳
    dateFormat (row, column) {
      let date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    //点击添加按钮触发
    openAddAndEditDialog (id) {
      this.title = id === 0 ? '添加角色' : '编辑角色'
      this.judgeId = id === 0 ? 0 : id
      this.isShowDialogComponent=true
    },
    //关闭对话框后传出事件
    handleClose (payload) {
      if(payload==='submitButton'){
        this.getRoleList()
      }
      this.isShowDialogComponent = false
    },
    //获取角色列表
    async getRoleList () {
      this.loading = true
      const res = await RoleManage.getRoleList(this.queryInfo)
      this.loading = false
      // console.log(res)
      this.roleList = res.ListData
      this.queryInfo.total = res.Total
    },
    //点击状态开关时触发
    async statusChange (rowInfo) {
      await RoleManage.statusChange(rowInfo.ID, rowInfo.Status)
      //做成功的后续操作
      this.$message.success('修改状态成功')
    },
    //点击分配权限触发
    async openSetRightsTree (rowInfo) {
      console.log(rowInfo)
      console.log(typeof rowInfo.JuIDList)
      const checkArray = rowInfo.JuIDList.split(',')
      this.defKeys = checkArray
      this.roleId = rowInfo.ID
      //调用递归函数
      this.getLeafKeys(rowInfo, this.defKeys)
      this.setRightsDialogVisible = true
      //调用接口
      const res = await RoleManage.setRights()
      console.log(res)
      this.rightsList = res
    },
    //通过递归的方式，获取角色下所有三级权限的ID，并保存到defKeys数组中
    getLeafKeys (node, arr) {
      if (!node.Children) {
        return arr.push(node.JuID)
      } else {
        node.Children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      }
    },

    //点击分配权限对话框中的确定按钮，进行真正的权限分配
    async setRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      let strId = '0'
      console.log(keys)
      if (keys.length !== 0) {
        strId = keys.toString()
      }

      console.log(strId)
      try {
        //发起网络请求
        await RoleManage.bindRights(this.roleId, strId)
        //做成功的后续操作
        this.$message.success('分配角色权限成功')
        this.setRightsDialogVisible = false
        await this.getRoleList()
      } catch (err) {
        //  console.log(err)
      }

    },
    //当点击关闭分配权限对话框时候，清空defKeys中的数据
    //下面的代码解决一闪而过的问题
    setRightsDialogClosed () {
      this.defKeys = []
      this.$nextTick(function () {
        this.$refs.treeRef.setCheckedKeys([])
      })
    },
    //点击删除按钮时候触发
    async deleteRoles (rowInfo) {
      // console.log(rowInfo)
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除该角色')
      } else {
        RoleManage.deleteRoles(rowInfo.ID)
        //进行成功的后续操作
        this.$message.success('删除角色信息成功')
        await this.getRoleList()
      }
    },
  }

}
</script>

<style scoped>
@import "../../../src/assets/style/realize/tableStyle.css";

.role-manage {
  background-color: #eee;
}

.second-card {
  position: relative;
  padding-bottom: 50px;
}

/deep/ .el-pagination {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.el-card {
  margin-top: 20px;
  box-shadow: none;
}

/*给表头一行加背景颜色*/
/deep/ .setHeaderSubjectColumnName {
  background-color: #E6E6FA !important;
  opacity: 0.7 !important;
}

</style>
